import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useState, useEffect, useRef } from "react";
import { getDsToZlData } from "../../api/DesignTableApi";
import { Card, Select, Modal, message, Col, Row, InputNumber, Form, Radio, } from "antd";
import { Button } from "devextreme-react/button";
import "./_style.less";
import Draggable from "react-draggable";
const TailDifferenceModalComponent = (props) => {
    const { isOpen, handleOpen, _this } = props;
    const [diffForm] = Form.useForm();
    const { setFieldsValue } = diffForm;
    const [selectColumnKey, setSelectColumnKey] = useState([]);
    const [columnData, setColumnData] = useState([]);
    const [disabled, setDisabled] = useState(true);
    const [bounds, setBounds] = useState({
        left: 0,
        top: 0,
        bottom: 0,
        right: 0,
    });
    const draggleRef = useRef(null);
    const getDefaultKeys = () => {
        return columnData && columnData.length ? [columnData[0].key] : [];
    };
    //获取列数据
    const getColumnData = () => {
        const headerColumn = _this.gridRef.headerService.headerColumn;
        const filterNumberColumn = headerColumn.filter((item) => {
            item["value"] = item.key; // ant design 下拉框使用 label 和  value;
            return item.config.type === "numeric";
        });
        setColumnData([...filterNumberColumn]);
        return filterNumberColumn;
    };
    const loadFetchApi = async () => {
        const columnData = getColumnData();
        const { tableConfig = {} } = _this.gridRef.getCpasTableGrid();
        let { tailDiffConf = {} } = tableConfig;
        // 如果配置中存储了值
        if (tailDiffConf && Object.keys(tailDiffConf).length > 0) {
            setFieldsValue(tailDiffConf);
            setSelectColumnKey(tailDiffConf.selectColumnKey);
        }
        else {
            // 如果配置中没有则走默认第一个
            const columnDefaultKey = getDefaultKeys();
            setFieldsValue({
                column_val: columnDefaultKey,
                diffType: "t1",
                fix_value: 100,
            });
            setSelectColumnKey(columnDefaultKey);
        }
    };
    useEffect(() => {
        loadFetchApi();
    }, [isOpen]);
    const onSelectChange = (value) => {
        setSelectColumnKey(value);
    };
    const onClearTable = async () => {
        const defaultSelectKey = getDefaultKeys();
        // 重置form表单
        setFieldsValue({
            column_val: defaultSelectKey,
            diffType: "t2",
            fix_value: 100,
        });
        // 清空 tableConfig
        delete _this.gridRef.tableConfig["tailDiffConf"];
        const dsSourceData = _this.gridRef.dsSourceData;
        const dsFormulaSourceData = _this.gridRef.props.dsTableRef.getFormulaSourceData();
        const tableConfig = _this.gridRef.tableConfig;
        try {
            // 重算整理数据
            const tid = _this?.gridRef?.props?.notes?.tid;
            const zlTableData = await getDsToZlData(dsSourceData, {
                ...tableConfig,
            }, dsFormulaSourceData, tid);
            if (zlTableData && zlTableData.data) {
                const zlTransformData = zlTableData.data;
                //zlGridData 除了拆表的转数逻辑 , 数据库会存储该数据
                //zlDivideData 拆表后的转数逻辑
                //zlGridData 存储在隐藏的CpasTable中，为了ref正确使用, 真正渲染调用afterDivideTableRender用数组。
                const { zlGridData, zlDivideData } = zlTransformData;
                await _this.gridRef.reloadTable(zlGridData, "zl", dsSourceData);
                const refs = await _this.gridRef.afterDivideTableRender(zlDivideData);
                //更新整理模式下cpastable实例
                _this.gridRef && _this.gridRef?.dsTableRef?.setZlCpasTableRefs(refs);
                handleOpen(false);
                message.success("尾差条件清空成功");
                _this.gridRef.setTableContentChange(true, {
                    type: "尾差清空",
                    params: {},
                });
            }
        }
        catch (e) {
            message.error("操作失败，请检查配置项重试");
            throw e;
        }
    };
    const onCancel = () => {
        console.log("onCancel");
        if (columnData && columnData.length) {
            setSelectColumnKey(getDefaultKeys());
        }
        else {
            setSelectColumnKey([]);
        }
        handleOpen(false);
    };
    const onFinishSave = async () => {
        let formValues = diffForm.getFieldsValue(); // 获取表单数据
        console.log("表单数据:", formValues);
        const dsSourceData = _this.gridRef.dsSourceData;
        console.log(dsSourceData, "dsSourceData111");
        const dsFormulaSourceData = _this.gridRef.props.dsTableRef.getFormulaSourceData();
        const { tableConfig } = _this.gridRef.getCpasTableGrid();
        let newTableCfg = {
            ...tableConfig,
        };
        // 通过单选按钮开关选择状态判断，用户是否选中了
        if (formValues.diffType) {
            newTableCfg = {
                ...newTableCfg,
                tailDiffConf: {
                    ...formValues,
                },
            };
        }
        console.log(newTableCfg, "newTableCfg");
        try {
            /**本地调试专用 */
            /*let zlTableData: any = {};
            const data = sortCpasTable(
              dsSourceData,
              newTableCfg,
            );
            zlTableData.data = data;*/
            const tid = _this?.gridRef?.props?.notes?.tid;
            const zlTableData = await getDsToZlData(dsSourceData, newTableCfg, dsFormulaSourceData, tid);
            if (zlTableData && zlTableData.data) {
                const zlTransformData = zlTableData.data;
                //zlGridData 除了拆表的转数逻辑 , 数据库会存储该数据
                //zlDivideData 拆表后的转数逻辑
                //zlGridData 存储在隐藏的CpasTable中，为了ref正确使用, 真正渲染调用afterDivideTableRender用数组。
                const { zlGridData, zlDivideData } = zlTransformData;
                await _this.gridRef.reloadTable(zlGridData, "zl", dsSourceData);
                const refs = await _this.gridRef.afterDivideTableRender(zlDivideData);
                //更新整理模式下cpastable实例
                console.log(refs, "refs1111");
                _this.gridRef && _this.gridRef?.dsTableRef?.setZlCpasTableRefs(refs);
                handleOpen(false);
                message.success("尾差条件设置成功");
                _this.gridRef.setTableContentChange(true, {
                    type: "尾差保存",
                    params: {
                        ...newTableCfg.sortCfg,
                    },
                });
            }
        }
        catch (e) {
            message.error("操作失败，请检查配置项重试");
            throw e;
        }
    };
    const tableSettingLeft = () => {
        return (_jsx(React.Fragment, { children: _jsxs("div", { style: { display: "flex", alignItems: "center" }, children: [_jsx("i", { className: "dx-icon-datafield", style: { color: "green", fontSize: 16 } }), " ", _jsx("span", { style: { marginLeft: 10 }, children: "\u5C3E\u5DEE" })] }) }));
    };
    const tableSettingRight = () => {
        return (_jsxs(React.Fragment, { children: [_jsx(Button, { onClick: () => onClearTable(), type: "default", children: "\u5C3E\u5DEE\u6E05\u7A7A" }), _jsx(Button, { onClick: onFinishSave, type: "default", children: "\u786E\u5B9A" })] }));
    };
    const onStart = (_event, uiData) => {
        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = draggleRef.current?.getBoundingClientRect();
        if (!targetRect) {
            return;
        }
        setBounds({
            left: -targetRect.left + uiData.x,
            right: clientWidth - (targetRect.right - uiData.x),
            top: -targetRect.top + uiData.y,
            bottom: clientHeight - (targetRect.bottom - uiData.y),
        });
    };
    return (_jsx(React.Fragment, { children: _jsx(Modal, { open: isOpen, width: "90%", onCancel: onCancel, footer: null, className: "setting zl-modal", keyboard: false, maskClosable: false, destroyOnClose: true, forceRender: true, title: _jsx(Card, { title: tableSettingLeft(), extra: tableSettingRight(), bordered: false, className: "merge-card-title", style: {
                    cursor: "move",
                }, onMouseOver: () => {
                    if (disabled) {
                        setDisabled(false);
                    }
                }, onMouseOut: () => {
                    setDisabled(true);
                }, 
                // fix eslintjsx-a11y/mouse-events-have-key-events
                // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/mouse-events-have-key-events.md
                onFocus: () => { }, onBlur: () => { } }), modalRender: (modal) => (_jsx(Draggable, { disabled: disabled, bounds: bounds, nodeRef: draggleRef, onStart: (event, uiData) => onStart(event, uiData), children: _jsx("div", { ref: draggleRef, children: modal }) })), children: _jsx("div", { className: "tail-diff-content filter-card-content", children: _jsx("div", { className: "filter-condition sort-condition", children: _jsxs(Form, { form: diffForm, name: "filter_form", layout: "inline", onFinish: onFinishSave, initialValues: {
                            diffType: "t1",
                            fix_value: 100,
                            column_val: columnData && columnData.length ? columnData[0].value : "",
                        }, children: [_jsx(Row, { style: { marginBottom: "16px" }, children: _jsx(Col, { span: 24, className: "cpas-row-block", children: _jsx(Form.Item, { name: "column_val", label: "\u8BF7\u9009\u62E9\u5217\uFF1A", children: _jsx(Select, { mode: "tags", size: "middle", onChange: onSelectChange, style: { width: "100%" }, options: columnData }) }) }) }), _jsx(Row, { children: _jsxs(Col, { span: 18, children: [_jsx(Form.Item, { name: "fix_value", label: "合计固定：", children: _jsx(InputNumber
                                            // defaultValue={100}
                                            // disabled={true}
                                            // onChange={(value) => {
                                            //   let formValues = diffForm.getFieldsValue(); // 获取表单数据
                                            //   setFieldsValue({
                                            //     ...formValues,
                                            //     fix_value: value,
                                            //   });
                                            // }}
                                            // min={0}
                                            // max={100}
                                            // formatter={(value) => `${value}%`}
                                            , {}) }), _jsx(Form.Item, { name: "diffType", children: _jsxs(Radio.Group, { children: [_jsx(Radio, { value: "t1", children: "\u8C03\u6574\u9996\u4E2A\u6709\u91D1\u989D\u7684\u884C" }), _jsx(Radio, { value: "t2", children: "\u8C03\u6574\u6700\u5927\u91D1\u989D" })] }) })] }) })] }) }) }) }) }));
};
export default TailDifferenceModalComponent;
